import { troggleActive } from "../../js/common.js"
import { initCheckboxGroup } from '/static/js/gd-ui/checkbox/group.js'

class CommonSearch {
    constructor() {
        this.filterOptionQueue = []
        this.mobileSearchTab = mobileSearchTab
        this.filterList = filterList
        this.tableHeader = tableHeader
        this.isShowSort = false
        this.hasData = true
        this.searchFnc = () => {}
        this.reqFilterOptionsFunc = () => {}

        this.hideTabMask = this.hideTabMask.bind(this)
        this.resetFilter = this.resetFilter.bind(this)
        this.showFilter = this.showFilter.bind(this)
        this.searchFilter = this.searchFilter.bind(this)
    }
    // 初始化页面动态渲染
    initRender() {
        if(gugeeGobal.isMobile) {
            this.initRenderTab()
        } else {
            this.initTableHeader()
            this.initPagination()
        }
        this.initRenderFilter()
        this.reqFilterOptions()
        this.initEvent()
        this.searchFnc()
    }
    // table表头动态渲染
    initTableHeader() {
        const table = document.getElementById('searchTable')
        const headerWrap = table.querySelector('thead tr')
        let thead = ''
        this.tableHeader.forEach(item => {
            thead += '<th'
            if(item.align) {
                thead += ' align="' + item.align + '"'
            }
            if(item.width) {
                thead += ' width="' + item.width + '"'
            }
            if(item.hasSort) {
                thead += ' class="is-sort'
                if(item.isActive) {
                    thead += ' is-active'
                }
                thead += '"'
                // sortEvent
                thead += ' data-sort="' + item.sortIndex + '"'
            }
            thead += '>'
            if(item.hasTip) {
                thead += '<div class="gd-popover"' +
                    ' content="' + item.tipContent + '">' + item.label
                if(item.hasSort) {
                    thead += '<i class="iconfont iconsort-down"></i>'
                }
                thead += '<i class="iconfont iconfaq"></i>' +
                    '</div>'
            } else {
                thead += item.label
                if(item.hasSort) {
                    thead += '<i class="iconfont iconsort-down"></i>'
                }
            }
            thead +='</th>'
        })
        headerWrap.innerHTML = thead
        headerWrap.querySelectorAll('th.is-sort').forEach(item => {
            item.addEventListener('click', () => {
                const sort = item.getAttribute('data-sort')
                this.changeTableSort(item, sort)
            })
        })
    }
    initPagination() {
        layui.use('laypage', () => {
            let laypage = layui.laypage;
            //执行一个laypage实例
            laypage.render({
                elem: 'pagination', //注意，这里的 test1 是 ID，不用加 # 号
                count: totalRow, //数据总数，从服务端得到
                prev: '<i class="iconfont iconicon_previous"></i>',
                next: '<i class="iconfont iconarrowright"></i>',
                jump: (obj, first) => {
                    if (!first) {
                        if (!gugeeGobal.isLogin) {
                            toLogin()
                            return false
                        }
                        params.page = obj.curr
                        this.searchFnc()
                    }
                }
            })
        })
    }
    initRenderTab() {
        const optionRows = document.querySelectorAll('.options-row')
        const tabFilterWrap = document.getElementById('tabFilterWrap')
        let str = ''
        let wrapStr = ''
        this.mobileSearchTab.forEach((item, i) => {
            str += '<div data-tab-index="' + i + '" '
            // 如果是tip或者自身有点击事件 则取消默认点击事件
            if(!item.hasTip && !item.isFilter) {
                str += 'data-default-click="1"'
            }
            if(item.roleId) {
                str += ' data-role-id="' + item.roleId + '"'
            }

            str += ' class="' + item.align + '"'
            if(item.isFilter) {
                str += ' is-filter="1"'
            }
            str += '>'
            if(item.hasTip) {
                str += '<div class="gd-popover"'
                if(item.tipTitle) {
                    str += ' data-title="' + item.tipTitle + '"'
                }
                str += 'content="' + item.tipContent + '">' +
                    '<span>' + item.label + '</span>' +
                    '<i class="iconfont iconfaq"></i>' +
                    '</div>'
            } else {
                str += '<span>' + item.label + '</span>'
                str += '<i class="iconfont ' + item.icon + '"></i>'
            }
            str += '</div>'

            if(item.type) {
                wrapStr += '<div class="tab-wrap-item" style="display: none;">'
                switch (item.type) {
                    case 1: {
                        wrapStr += '<div class="gd-btn-select" data-sort-index="' + i + '">' +
                            '<ul class="btn-select">'
                        if(item.options) {
                            item.options.forEach(option => {
                                wrapStr += '<li class="btn-select-item'
                                if(option.isActive) {
                                    wrapStr += ' is-active'
                                }
                                wrapStr +='" value="' + option.value + '">' + option.label + '</li>'
                            })
                        }
                        wrapStr += '</ul>' +
                            '</div>'
                        break
                    }
                    case 2: {
                        wrapStr += '<ul class="tab-filter-list" data-sort-index="' + i + '"></ul>'
                        break
                    }
                }
                wrapStr += '</div>'
            }
        })
        tabFilterWrap.innerHTML = wrapStr
        optionRows.forEach(row => {
            row.innerHTML = str
            row.querySelectorAll('[is-filter="1"]').forEach(item => {
                item.addEventListener('click', this.showFilter)
            })

            const rowRights = row.querySelectorAll('.right')
            const rowLefts = row.querySelectorAll('.left')
            const rightItemSize = rowRights.length
            if(rightItemSize > 1) {
                rowRights.forEach(rightItem => {
                    rightItem.style.flex = '0'
                })
                rowLefts.forEach(leftItem => {
                    leftItem.style.flex = '1'
                })
            }
        })
        if(str.indexOf('gd-popover') > -1) {
            initPopover()
        }
    }
    initRenderFilter() {
        let filterWrapStr = ''
        if(gugeeGobal.isMobile) {
            this.filterList.forEach(item => {
                // 如果属于页面选项，则只请求内容，不渲染页面
                if(item.isMobileTab) {
                    if(item.requestOption) {
                        //全局筛选项请求队列
                        this.filterOptionQueue.push(_axios.get(item.optionUrl))
                    }
                    return true
                }
                if(item.isInline) {
                    item.items.forEach(inlineItem => {
                        filterWrapStr += this._renderFilterItem(inlineItem)
                    })
                } else {
                    filterWrapStr += this._renderFilterItem(item)
                }
            })
            filterWrap.querySelector('.content').innerHTML = filterWrapStr
            if(gugeeOS.isIPhone) {
                filterWrap.style.height = 'calc(100vh - 115px)'
            }
        } else {
            /**
             *  type 0: 选项 1:input 2.select 3:checkbox-group
             */
            this.filterList.forEach(item => {
                filterWrapStr += '<div class="filter-item">'
                if(item.label) {
                    filterWrapStr += '<div class="label">' + item.label + ' : </div>'
                }
                if(item.isInline) {
                    filterWrapStr += '<div class="item-wrap">'
                    item.items.forEach(inlineItem => {
                        filterWrapStr += '<div class="inline-item">'
                        if(inlineItem.label) {
                            filterWrapStr += '<div class="label">' + inlineItem.label + ':</div>'
                        }
                        filterWrapStr += this._renderFilterItem(inlineItem)
                        filterWrapStr += '</div>'
                    })
                    filterWrapStr += '</div>'
                } else {
                    filterWrapStr += '<div class="item-wrap">'
                    filterWrapStr += this._renderFilterItem(item)
                    filterWrapStr += '</div>'
                }
                filterWrapStr += '</div>'
            })
            filterWrapStr += '<div class="filter-item" id="selectedFilterItem" style="display: none;">' +
                '<div class="label">Selected:</div>' +
                '<div class="selected-wrap" id="selectedWrap"></div>' +
                '<div class="right">Clear</div>' +
                '</div>'

            filterWrap.innerHTML = filterWrapStr

            if(!gugeeGobal.isLogin) {
                showLock(filterWrap, {
                    // inner: 'Please <a href="javascript:;" onclick="toLogin()">log in</a> to use this feature.'
                    inner: 'Please <a href="javascript:;">log in</a> to use this feature.'
                })
                filterWrap.querySelector('.lock-wrap a').addEventListener('click', toLogin)
                /*document.querySelectorAll('.td-audience').forEach(item => {
                    showLock(item, {
                        inner: 'Please <a href="javascript:;" onclick="toLogin()">log in</a> to use this feature.'
                    })
                })*/
            } else {
                if(gugeeGobal.roleId < 3) {
                    showLock(filterWrap, {
                        roleId: 3
                    })
                    /*document.querySelectorAll('.td-audience').forEach(item => {
                        showLock(item, {
                            roleId: 3
                        })
                    })*/
                    const upgradeEle = document.querySelector('.list-footer-tx .text-link')
                    upgradeEle && upgradeEle.addEventListener('click', () => {
                        window.location.href = '/pricing?refer=' + window.location.href
                    })
                }
            }
        }
    }
    initEvent() {
        initCheckboxGroup()

        if(gugeeGobal.isMobile) {
            if(inputPlaceholder) {
                const insKeyword = document.getElementById('insKeyword')
                insKeyword.setAttribute('placeholder', inputPlaceholder)
            }

            const mask = document.getElementById('mask')
            const el_sort = document.querySelectorAll('.options-row>[data-default-click="1"]')
            const tabFilterWrap = document.getElementById('tabFilterWrap')
            el_sort.forEach(item => {
                item.addEventListener('click', () => {
                    if(!gugeeGobal.isLogin) {
                        toLogin()
                        return false
                    }
                    const roleId = item.getAttribute('data-role-id')
                    if(roleId && (roleId >= gugeeGobal.roleId)) {
                        this._showNoPermission()
                        return false
                    }

                    if (this.isShowSort) {
                        this.hideTabMask()
                        tabFilterWrap.hide()
                    } else {
                        this.showTabMask()
                        tabFilterWrap.querySelectorAll('.tab-wrap-item').forEach(item => item.hide())
                        const index = item.getAttribute('data-tab-index')
                        tabFilterWrap.querySelector('.tab-wrap-item [data-sort-index="' + index + '"]').parentElement.show()
                        tabFilterWrap.show()
                        this.isShowSort = true
                    }
                })
            })
            document.querySelectorAll('#tabFilterWrap .btn-select-item').forEach(item => {
                item.addEventListener('click', e => {
                    if(!item.classList.contains('is-active')) {
                        item.parentElement.querySelector('.is-active').classList.remove('is-active')
                        item.classList.add('is-active')
                        params.sort = item.getAttribute('value')
                        this.hideTabMask()
                        const sortInx = e.target.parentElement.parentElement.getAttribute('data-sort-index')

                        const tabs = document.querySelectorAll('.options-row [data-tab-index="' + sortInx + '"]')
                        tabs.forEach(tab => {
                            tab.querySelector('span').innerText = item.innerText
                        })
                        this.searchFnc()
                        this.isShowSort = false
                    }
                })
            })

            // mask 事件
            const maskContent = document.getElementById('maskContent')
            maskContent.addEventListener('click', (e) => {
                e.stopPropagation()
            })
            mask.addEventListener('click', e => {
                this.hideTabMask()
                this.isShowSort = false
                e.preventDefault()
            })

            // search 输入事件
            const insKeyword = document.getElementById('insKeyword')
            insKeyword.addEventListener('input', debounce(() => {
                params.page = 1
                this.searchFnc()
            }, 500))

            //filter事件
            filterWrap.querySelectorAll('.btn-select-item').forEach(ele => {
                ele.addEventListener('click', () => {
                    if(!ele.classList.contains('is-active')) {
                        if(gugeeGobal.roleId <= 2) {
                            this.hideFilter()
                            this._showNoPermission()
                            return false
                        }
                        const parentEle = ele.parentElement
                        parentEle.querySelector('.is-active').classList.remove('is-active')
                        ele.classList.add('is-active')
                        const paramKey = parentEle.getAttribute('data-param-key')
                        params[paramKey] = ele.getAttribute('value')
                    }
                })
            })
            // input event
            filterWrap.querySelectorAll('.gd-input').forEach(ele => {
                ele.addEventListener('blur', e => {
                    params[e.target.name] = e.target.value
                })
            })

            //重置选项
            filterWrap.querySelector('.filter-footer .btn-default').addEventListener('click', this.resetFilter)
            filterWrap.querySelector('.filter-footer .btn-info').addEventListener('click', this.searchFilter)

            if(gugeeGobal.isLogin) {
                window.addEventListener('scroll', debounce(() => {
                    if (!this.hasData) {
                        return
                    }
                    if ((+(getScroll().top + screen.height + 200)) >= getScroll().height) {
                        params.page++
                        this.searchFnc()
                    }
                }))
            }

            const viewMoreEle = document.querySelector(' .link-login')
            viewMoreEle && viewMoreEle.addEventListener('click', () => {
                toLogin()
            })
        } else {
            const upgradeEle = document.querySelector('tfoot .text-link')
            upgradeEle && upgradeEle.addEventListener('click', () => {
                window.location.href = '/pricing?refer=' + window.location.href
            })

            document.querySelector('#mainSearch .btn-info').addEventListener('click', this.searchFilter)
            document.querySelector('#mainSearch .btn-filter').addEventListener('click', this.showFilter)
            document.querySelector('#selectedFilterItem > .right').addEventListener('click', this.resetFilter)
        }
    }
    getList(wrap, url, listFn, loadedFn) {
        _axios.get(url).then(res => {
            if (res.Code === 200) {
                const data = res.Data
                const list = data.list
                let str = ''
                if (gugeeGobal.isMobile) {
                    const rorate = document.querySelector('.gd-mobile-list__footer .rotate')
                    const footerText = document.querySelector('.gd-mobile-list__footer .list-footer-tx')
                    if (data.totalRow === 0) {
                        wrap.innerHTML = ''
                        showNoDataImg(wrap)
                        rorate && rorate.hide()
                        footerText && footerText.hide()
                        this.hasData = false
                        if (!gugeeGobal.isLogin) {
                            document.querySelector('.gd-mobile-list__footer').hide()
                        }
                        wrap.removeAttribute('style')
                    } else {
                        if (!gugeeGobal.isLogin) {
                            document.querySelector('.gd-mobile-list__footer').show()
                        }
                        if (data.lastPage) {
                            this.hasData = false
                            rorate && rorate.hide()
                            footerText && (() => {
                                footerText.innerHTML = 'You have reached the end.'
                                footerText.show()
                            })()
                            wrap.style.minHeight = 'auto'
                        } else {
                            this.hasData = true
                            rorate && rorate.show()
                            footerText && footerText.hide()
                        }
                        str += listFn(list)

                        if (params.page === 1) {
                            wrap.innerHTML = str
                        } else {
                            wrap.innerHTML = wrap.innerHTML + str
                        }
                        loadedFn && loadedFn()
                    }
                } else {
                    if (params.page === 1) {
                        totalRow = data.totalRow
                        this.initPagination()
                    }
                    if (data.totalRow === 0) {
                        showNoDataImg(wrap, {
                            isTable: true
                        })
                    } else {
                        wrap.innerHTML = listFn(list)
                        loadedFn && loadedFn()
                        initPopover()
                        /*if(!gugeeGobal.isLogin || (gugeeGobal.isLogin && gugeeGobal.roleId < 3)) {
                            document.querySelectorAll('.td-audience').forEach(item => {
                                showLock(item, {
                                    roleId: 3
                                })
                            })
                        }*/
                    }
                }
            } else if (res.Code === 403) {
                if (gugeeGobal.isMobile) {
                    const rorate = document.querySelector('.gd-mobile-list__footer .rotate')
                    const footerText = document.querySelector('.gd-mobile-list__footer .list-footer-tx')
                    rorate.hide()
                    footerText.innerHTML = res.Msg
                    footerText.show()
                    this.hasData = false

                    const upgradeEle = document.querySelector('.list-footer-tx .text-link')
                    upgradeEle.addEventListener('click', () => {
                        window.location.href = '/pricing?refer=' + window.location.href
                    })
                }
            }
            wrap.hideLoading()
        })
    }
    initFilterSearch() {
        if(!gugeeGobal.isMobile) {
            this.initSelectItem()
            this.initInputEvent()
        }

        this.initChechboxEvent()
    }
    initSelectItem () {
        const selectItems = document.querySelectorAll('.select-item > li')
        selectItems.forEach(item => {
            item.addEventListener('click', event => {
                const element = event.target
                const parentElement = element.parentElement
                troggleActive(element, () => {
                    params.page = 1
                    const paramKey = parentElement.getAttribute('data-param-key')
                    const value = element.getAttribute('value')
                    const isDefault = value && value !== '0'
                    if(isDefault) {
                        params[paramKey] = value
                    } else {
                        params[paramKey] = undefined
                    }
                    const label = parentElement.previousElementSibling || parentElement.parentElement.previousElementSibling
                    this.filterSelectedWrapEvent(event, {
                        label: label.innerText.replace(':',''),
                        paramKey,
                        value: isDefault ? element.innerText : undefined
                    })
                    this.searchFnc()
                })
            })
        })
    }
    initInputEvent() {
        const inputs = document.querySelectorAll('main .gd-input')
        inputs.forEach(input => {
            input.addEventListener('focus', () => {
                if(gugeeGobal.roleId < 3) {
                    let config = {
                        class: '',
                        content: 'Only available for ADVANCED version users or higher,upgrade now!',
                        confirmBtnText: 'Upgrade',
                        confirmBtn: {
                            event: () => {
                                showLoading()
                                window.location.href = '/pricing?refer=' + window.location.href
                            }
                        },
                        cancelBtnText: 'Not Now',
                    }
                    showModal(config)
                }
            })
            input.addEventListener('blur', event => {
                const element = event.target
                params[element.name] = element.value
                params.page = 1

                const label = element.parentElement.previousElementSibling || element.parentElement.parentElement.previousElementSibling
                this.filterSelectedWrapEvent(event, {
                    label: label.innerText.replace(':',''),
                    paramKey: element.name,
                    value: element.value
                })
                this.searchFnc()
            })
            if(!gugeeGobal.isMobile) {
                input.addEventListener('keydown', e => {
                    if(e.key === 'Enter') {
                        input.blur()
                    }
                })
            }
        })
    }
    initChechboxEvent() {
        const groups = document.querySelectorAll('.gd-checkbox-group')
        groups.forEach(group => {
            const checkboxs = group.querySelectorAll('.gd-checkbox')
            const paramKey = group.getAttribute('data-param-key')
            checkboxs.forEach(checkbox => {
                checkbox.addEventListener('click', event => {
                    const input = checkbox.querySelector('input[type="checkbox"]')
                    let value = checkbox.querySelector('.label').innerText
                    if(input.checked) {
                        params[paramKey] = checkbox.getAttribute('value')
                    } else {
                        params[paramKey] = undefined
                        value = undefined
                    }

                    const label = group.parentElement.previousElementSibling
                    this.filterSelectedWrapEvent(event, {
                        label: label.innerText.replace(':',''),
                        paramKey,
                        value,
                    })
                    if(!gugeeGobal.isMobile) {
                        this.searchFnc()
                    }
                })
            })
        })
    }
    filterSelectedWrapEvent(e, data) {
        if (!gugeeGobal.isMobile) {
            const selectedFilterItem = document.getElementById('selectedFilterItem')
            const selectedWrap = document.getElementById('selectedWrap')
            const selectedItem = selectedWrap && selectedWrap.querySelector('[data-label="' + data.label + '"]')
            if (selectedItem) {
                if(data.value) {
                    selectedItem.querySelector('.selected-item__inner').innerHTML = '<span>' + data.label + ' : </span>' + data.value
                } else {
                    selectedItem.remove()
                    params[data.paramKey] = undefined
                    if(!selectedWrap.innerHTML) {
                        selectedFilterItem.hide()
                    }
                    return false
                }
            } else {
                if(data.value) {
                    const item = document.createElement('div')
                    item.className = 'selected-item'
                    item.setAttribute('data-label', data.label)
                    const inner = document.createElement('div')
                    inner.className = 'selected-item__inner'
                    inner.innerHTML = '<span>' + data.label + ': </span>' + data.value
                    item.appendChild(inner)
                    const icon = document.createElement('i')
                    icon.className = 'iconfont iconbuzhichi'
                    icon.addEventListener('click', () => {
                        item.remove()
                        params[data.paramKey] = undefined
                        params.page = 1
                        const element = e.target
                        const parentElement = element.parentElement
                        if(element.classList.contains('gd-input')) {
                            element.value = ''
                        } else if(element.classList.contains('gd-option')) {

                            if(data.label === 'Primary') {
                                this.clearSecondarySelect()
                            } else {
                                if(parentElement) {
                                    parentElement.parentElement.parentElement.querySelector('.label').innerText = data.label
                                    parentElement.querySelector('.is-active').classList.remove('is-active')
                                    parentElement.querySelector('li:first-child').classList.add('is-active')
                                }
                            }
                        } else if(parentElement.classList.contains('gd-checkbox')) {
                            const group = parentElement.parentElement
                            group.querySelectorAll('input[type="checkbox"]').forEach(input => {
                                input.checked = false
                            })
                        } else {
                            // select-item
                            const oldEle = document.querySelector('[data-param-key="' + data.paramKey + '"]')
                            oldEle.querySelector('.is-active').classList.remove('is-active')
                            const newEle = oldEle.querySelector('[value="0"]') || oldEle.querySelector('li:first-child')
                            newEle.classList.add('is-active')
                        }

                        if(!selectedWrap.innerHTML) {
                            selectedFilterItem.hide()
                        }
                        // 是否是清空全部选项触发的点击事件
                        if(!isClearAll) {
                            this.searchFnc()
                        }
                    })
                    item.appendChild(icon)
                    selectedWrap.appendChild(item)
                    selectedFilterItem.show('flex')
                }
            }
        }
    }
    clearSecondarySelect() {
        const element = document.querySelector('[data-label="Secondary"]')
        element.parentElement.parentElement.querySelector('.label').innerText = 'Secondary'
        element.innerHTML = ''
    }
    changeTableSort(el, sort) {
        if(!gugeeGobal.isLogin) {
            toLogin()
            return false
        }
        troggleActive(el, () => {
            params.sort = sort
            params.page = 1

            this.searchFnc()
        })
    }
    hideFilter() {
        hideMask()
        mobileHeader.removeAttribute('style')
        filterWrap.hide()
    }
    showFilter() {
        if(gugeeGobal.isMobile) {
            if(!gugeeGobal.isLogin) {
                toLogin()
                return false
            }
            if(gugeeGobal.roleId < 2) {
                this._showNoPermission()
                return false
            }
            document.getElementById('mask').hide()
            mobileHeader.style.zIndex = '1'
            filterWrap.style.top = getScroll().top + 'px'
            filterWrap.show('flex')
            showMask({
                event: () => {
                    this.hideFilter()
                }
            })
        } else {
            const searchBg = document.getElementById('userSearch')
            if(filterWrap.toggleShow()) {
                searchBg.style.paddingBottom = '0'
            } else {
                searchBg.removeAttribute('style')
            }
        }
    }
    showTabMask() {
        const mask = document.getElementById('mask')
        mask.style.top = getScroll().top + 'px'
        mask.show()
        document.body.style.overflow = 'hidden'

        //header 显示
        document.querySelector('header').style.zIndex = '202'
    }
    hideTabMask() {
        const mask = document.getElementById('mask')
        mask.hide()
        document.body.style.overflow = 'auto'

        document.querySelector('header').removeAttribute('style')
    }
    _renderFilterItem(item) {
        let filterWrapStr = ''
        if(gugeeGobal.isMobile) {
            switch (item.type){
                case 1:
                    filterWrapStr += '<div class="select-item">' +
                        '<div class="select-title">' + item.label + '</div>' +
                        '<div class="gd-input-wrap">' +
                        '<input type="text" name="' + item.key + '" class="gd-input" placeholder="' + item.placeHolder + '">' +
                        '</div>'
                    break
                case 2:
                    filterWrapStr += '<div class="select-item">' +
                        '<div class="select-title">' + item.selectDefaultLabel + '</div>'
                    filterWrapStr += '<div class="gd-select" tabindex="0" role="select">' +
                        '<div class="gd-select-title">' +
                        '<div class="label">' + item.selectDefaultLabel + '</div>' +
                        '<i class="iconfont icondown1"></i>' +
                        '</div>' +
                        '<div class="gd-select-wrap">' +
                        '<ul data-param-key="' + item.key + '" data-label="' + item.selectDefaultLabel + '">'
                    if(item.requestOption) {
                        const url = item.requestParams?getEncodeUrl(item.optionUrl, item.requestParams):item.optionUrl
                        this.filterOptionQueue.push(_axios.get(url))
                    }
                    if(item.options) {
                        item.options.forEach(option => {
                            filterWrapStr += '<li class="gd-option" role="option" aria-selected="true"'
                            if(option.value) {
                                filterWrapStr += ' value="' + option.value + '"'
                            }
                            filterWrapStr += '">' + option.label + '</li>'
                        })
                    }
                    filterWrapStr += '</ul>' +
                        '</div>' +
                        '</div>'
                    filterWrapStr += '</div>'
                    break
                case 3:
                    filterWrapStr += '<div class="select-item">' +
                        '<div class="select-title">' + item.label + '</div>'
                    filterWrapStr += '<div class="gd-checkbox-group vertical" single data-param-key="' + item.key + '">'
                    if(item.options) {
                        item.options.forEach(option => {
                            filterWrapStr += '<div class="gd-checkbox" value="' + option.value + '">' +
                                '<input type="checkbox">' +
                                '<div class="label">' + option.label + '</div>' +
                                '</div>'
                        })
                    }
                    filterWrapStr += '</div>' +
                        '</div>'
                    break
                default:
                    filterWrapStr += '<div class="gd-btn-select select-item">' +
                        '<div class="label">' + item.label + '</div>' +
                        '<ul class="btn-select" data-param-key="' + item.key + '">'
                    item.options.forEach(option => {
                        filterWrapStr += '<li class="btn-select-item'
                        if(option.value === 0) {
                            filterWrapStr += ' is-active'
                        }
                        filterWrapStr +='" value="' + option.value + '">' + option.label + '</li>'
                    })
                    filterWrapStr += '</ul>'
            }
            filterWrapStr += '</div>'
        } else {
            switch (item.type) {
                case 1:
                    filterWrapStr += '<div class="gd-input-wrap">'
                    filterWrapStr += '<input type="text" id="' + item.key + '" name="' + item.key + '" class="gd-input" ' +
                        'placeholder="' + item.placeHolder + '">' +
                        '</div>'
                    break
                case 2:
                    filterWrapStr += '<div class="gd-select" tabindex="0" role="select">' +
                        '<div class="gd-select-title">' +
                        '<div class="label">' + item.selectDefaultLabel + '</div>' +
                        '<i class="iconfont icondown1"></i>' +
                        '</div>' +
                        '<div class="gd-select-wrap">' +
                        '<ul data-param-key="' + item.key + '" data-label="' + item.selectDefaultLabel + '">'
                    if(item.requestOption) {
                        const url = item.requestParams?getEncodeUrl(item.optionUrl, item.requestParams):item.optionUrl
                        this.filterOptionQueue.push(_axios.get(url))
                    }
                    if(item.options) {
                        item.options.forEach(option => {
                            filterWrapStr += '<li class="gd-option" role="option" aria-selected="true"'
                            if(option.value) {
                                filterWrapStr += ' value="' + option.value + '"'
                            }
                            filterWrapStr += '">' + option.label + '</li>'
                        })
                    }
                    filterWrapStr += '</ul>' +
                        '</div>' +
                        '</div>'
                    break
                case 3:
                    filterWrapStr += '<div class="gd-checkbox-group" single data-param-key="' + item.key + '">'
                    if(item.options) {
                        item.options.forEach(option => {
                            filterWrapStr += '<div class="gd-checkbox" value="' + option.value + '">' +
                                '<input type="checkbox">' +
                                '<div class="label">' + option.label + '</div>' +
                                '</div>'
                        })
                    }
                    filterWrapStr += '</div>'
                    break
                default:
                    if(item.requestOption) {
                        const url = item.requestParams?getEncodeUrl(item.optionUrl, item.requestParams):item.optionUrl
                        this.filterOptionQueue.push(_axios.get(url))
                    } else {
                        filterWrapStr += '<ul class="select-item" data-param-key="' + item.key + '">'
                        if(item.options) {
                            item.options.forEach(option => {
                                filterWrapStr += '<li value="' + option.value + '"'
                                if(option.value === 0) {
                                    filterWrapStr += ' class="is-active"'
                                }
                                filterWrapStr += '>' + option.label + '</li>'
                            })
                        }
                    }
                    filterWrapStr += '</ul>'
            }
        }
        return filterWrapStr
    }
    _showNoPermission() {
        showModal({
            class: '',
            content: 'Only available for ADVANCED version users or higher,upgrade now!',
            confirmBtnText: 'Upgrade',
            confirmBtn: {
                event: () => {
                    window.location.href = '/pricing?refer=' + window.location.href
                }
            },
            cancelBtnText: 'Not Now',
        })
    }
    searchFilter() {
        params.page = 1
        this.searchFnc()
    }
    resetFilter() {
        params = Object.assign({}, initParams)
        if(gugeeGobal.isMobile) {
            filterWrap.querySelectorAll('.is-active').forEach(item => {
                item.classList.remove('is-active')
            })
            filterWrap.querySelectorAll('.btn-select-item[value="0"]').forEach(item => {
                item.classList.add('is-active')
            })
            filterWrap.querySelectorAll('.gd-option:first-child').forEach(item => {
                item.classList.add('is-active')
                item.parentElement.parentElement.previousElementSibling.querySelector('.label').innerText = item.innerText
            })
            filterWrap.querySelectorAll('.gd-input').forEach(inputEle => {
                inputEle.value = ''
            })
            filterWrap.querySelectorAll('.gd-checkbox input[type="checkbox"]').forEach(item => {
                item.checked = false
            })
        } else {
            isClearAll = true
            let event = document.createEvent('Event')
            event.initEvent('click', true, true)
            document.querySelectorAll('#selectedWrap .iconfont').forEach(item => {
                item.dispatchEvent(event)
            })
            document.getElementById('insKeyword').value = ''
            this.searchFnc()
            isClearAll = false
        }
    }
    reqFilterOptions () {
        if(this.filterOptionQueue.length > 0) {
            Promise.all(this.filterOptionQueue).then(this.reqFilterOptionsFunc).catch(err => {
                console.error(err)
            })
        }
    }
    initTabSelect() {
        const list = document.querySelectorAll('.tab-filter-list li')
        list.forEach(item => {
            item.addEventListener('click', e => {
                if(!e.target.classList.contains('is-active')) {
                    const parent = e.target.parentElement
                    const oldActiveEle = parent.querySelector('.is-active')
                    oldActiveEle.classList.remove('is-active')
                    oldActiveEle.querySelector('.right').remove()
                    e.target.classList.add('is-active')
                    const tabInx = parent.getAttribute('data-sort-index')

                    const value = e.target.getAttribute('value')
                    document.querySelectorAll('.options-row [data-tab-index="' + tabInx + '"]').forEach(item => {
                        if(value) {
                            item.querySelector('span').innerHTML = value
                        } else {
                            item.querySelector('span').innerHTML = parent.getAttribute('label')
                        }
                    })

                    params[parent.getAttribute('data-param-key')] = value || undefined

                    this.hideTabMask()
                    this.isShowSort = false
                    params.page = 1
                    this.searchFnc()
                    e.target.innerHTML = e.target.innerHTML + '<div class="right"> <i class="iconfont iconzhichi"></i></div>'
                }
            })
        })
    }
    setSearchFunc(func) {
        this.searchFnc = () => {
            func()
        }
    }
    setReqFilterOptionsFunc(func) {
        this.reqFilterOptionsFunc = func
    }
}

/*
function initTabSelect() {
    const list = document.querySelectorAll('.tab-filter-list li')
    list.forEach(item => {
        item.addEventListener('click', e => {
            if(!e.target.classList.contains('is-active')) {
                const parent = e.target.parentElement
                const oldActiveEle = parent.querySelector('.is-active')
                oldActiveEle.classList.remove('is-active')
                oldActiveEle.querySelector('.right').remove()
                e.target.classList.add('is-active')
                const tabInx = parent.getAttribute('data-sort-index')

                const value = e.target.getAttribute('value')0
                document.querySelectorAll('.options-row [data-tab-index="' + tabInx + '"]').forEach(item => {
                    if(value) {
                        item.querySelector('span').innerHTML = value
                    } else {
                        item.querySelector('span').innerHTML = parent.getAttribute('label')
                    }
                })

                params[parent.getAttribute('data-param-key')] = value || undefined

                hideTabMask()
                isShowSort = false
                searchUser()
                e.target.innerHTML = e.target.innerHTML + '<div class="right"> <i class="iconfont iconzhichi"></i></div>'
            }
        })
    })
}*/
/*function searchFilter() {
    params.page = 1
    searchUser()
}*/
/*function searchKeyWord(e) {
    return function () {
        if (searchTikTokerTimer) {
            clearTimeout(searchTikTokerTimer)
        }
        searchTikTokerTimer = setTimeout(() => {
            searchTikTokerTimer = null
            params.userName = e.value
            params.page = 1
            searchUser()
        }, 500)
    }
}*/

/*function showMoreSearchItem(e) {
    const icon = e.querySelector('.iconfont')
    const con = e.parentNode.querySelector('.content')
    if (icon.classList.contains('is-reverse')) {
        con.show()
    } else {
        con.hide()
    }
    icon.classList.toggle('is-reverse')
}*/

/*function showFilter() {
    if(!gugeeGobal.isLogin) {
        toLogin()
        return false
    }
    if(gugeeGobal.roleId < 2) {
        showNoPermission()
        return false
    }
    document.getElementById('mask').hide()
    mobileHeader.style.zIndex = 1
    filterWrap.style.top = getScroll().top + 'px'
    filterWrap.show('flex')
    showMask({
        event: () => {
            hideFilter()
        }
    })
}*/

/*function hideFilter() {
    hideMask()
    mobileHeader.removeAttribute('style')
    filterWrap.hide()
}*/
/*function showTabMask() {
    const mask = document.getElementById('mask')
    mask.style.top = getScroll().top + 'px'
    mask.show()
    document.body.style.overflow = 'hidden'

    //header 显示
    document.querySelector('header').style.zIndex = '202'
}*/
/*function hideTabMask() {
    const mask = document.getElementById('mask')
    mask.hide()
    document.body.style.overflow = 'auto'

    document.querySelector('header').removeAttribute('style')
}*/

/*function showSortType() {
    document.getElementById('sortType').show()
}*/

/*function clearAll() {
    params = Object.assign({}, initParams)
    document.querySelectorAll('.filter .is-active').forEach(item => {
        item.classList.remove('is-active')
    })
    document.querySelectorAll('.filter .btn-select-item[value="0"]').forEach(item => {
        item.classList.add('is-active')
    })
    document.querySelectorAll('.filter .gd-option:first-child').forEach(item => {
        item.classList.add('is-active')
        item.parentElement.parentElement.previousElementSibling.querySelector('.label').innerText = item.innerText
    })
    document.querySelectorAll('.filter .gd-input').forEach(inputEle => {
        inputEle.value = ''
    })
    document.querySelectorAll('.filter .gd-checkbox input[type="checkbox"]').forEach(item => {
        item.checked = false
    })
}*/

export default CommonSearch